<template>
  <div class="customer-management">
    <!-- 选项卡导航 -->
    <el-tabs class="mt0" v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="客户档案" name="profile">
        <tab-profile v-if="activeTab==='profile'"></tab-profile>
      </el-tab-pane>

      <el-tab-pane label="客户账户" name="account">
        <tab-account v-if="activeTab==='account'"></tab-account>
        <div class="tab-content">

          <!-- 合计行 -->
          <div class="total-row">
            合计: <span class="total-amount">¥{{ totalAvailableBalance }}</span>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 客户档案添加/编辑表单 -->
    <el-dialog
      title="客户档案"
      :visible.sync="dialogVisible"
      width="80%"
      custom-class="custom-dialog">
      <el-tabs v-model="activeFormTab">
        <el-tab-pane label="基本信息" name="基本信息">
          <el-form
            ref="customerForm"
            :model="customerForm"
            :rules="rules"
            label-width="100px"
            label-position="right">
            <el-row>
              <el-col :span="8">
                <el-form-item label="客户编号" prop="customerCode">
                  <el-input v-model="customerForm.cusCode" :disabled="isEdit" placeholder="为空自动编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="*客户简称" prop="shortName">
                  <el-input v-model="customerForm.cusAbbName" placeholder="请输入客户简称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="*客户全称" prop="fullName">
                  <el-input v-model="customerForm.cusName" placeholder="请输入客户全称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="*业务类型" prop="businessType">
                  <el-select v-model="customerForm.busType" placeholder="请选择">
                    <el-option label="TMS" value="TMS"></el-option>
                    <el-option label="WMS" value="WMS"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户类型" prop="customerType">
                  <el-select v-model="customerForm.cusType" placeholder="请选择">
                    <el-option label="VIP" value="VIP"></el-option>
                    <el-option label="直客" value="直客"></el-option>
                    <el-option label="同行" value="同行"></el-option>
                    <el-option label="集运" value="集运"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="业务员" prop="salesman">
                  <el-input v-model="customerForm.salesmanOne" placeholder="请输入业务员"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="对接平台" prop="platform">
                  <el-select v-model="customerForm.platform" placeholder="请选择">
                    <el-option label="字节跳动ERP" value="字节跳动ERP"></el-option>
                    <el-option label="平台二" value="platform2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系人" prop="contact">
                  <el-input v-model="customerForm.cusPerson" placeholder="请输入联系人"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="customerForm.cusPhone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="16">
                <el-form-item label="地址" prop="address">
                  <el-input v-model="customerForm.companyAddress" placeholder="请输入详细地址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="customerForm.remark"
                    placeholder="请输入备注，50字内，非必填"
                    maxlength="50"
                    show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="logo" prop="logo">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadAction"
                    :headers="headers"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleUploadSuccess">
                    <img v-if="customerForm.logo" :src="customerForm.logo" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="结算信息" name="结算信息">
          <el-form
            ref="settlementForm"
            :model="customerForm"
            :rules="settlementRules"
            label-width="100px"
            label-position="right">
            <el-row>
              <el-col :span="8">
                <el-form-item label="*结算币种" prop="settlementCurrency">
                  <el-select v-model="customerForm.currency" placeholder="请选择">
                    <el-option label="USD" value="USD"></el-option>
                    <el-option label="CNY" value="CNY"></el-option>
                    <el-option label="GBP" value="GBP"></el-option>
                    <el-option label="UKL" value="UKL"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结算方式" prop="settlementMethod">
                  <el-select v-model="customerForm.settlementMethod" placeholder="请选择">
                    <el-option label="月结30天" value="月结30天"></el-option>
                    <el-option label="月结45天" value="月结45天"></el-option>
                    <el-option label="月结60天" value="月结60天"></el-option>
                    <el-option label="月结90天" value="月结90天"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结算周期" prop="settlementCycle">
                  <el-input v-model="customerForm.settlementPeriod" placeholder="请输入结算周期"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="支付方式" prop="paymentMethod">
                  <el-select v-model="customerForm.paymentMethod" placeholder="请选择">
                    <el-option label="转账" value="转账"></el-option>
                    <el-option label="现金" value="现金"></el-option>
                    <el-option label="微信" value="微信"></el-option>
                    <el-option label="支付宝" value="支付宝"></el-option>
                    <el-option label="ETC" value="ETC"></el-option>
                    <el-option label="油卡" value="油卡"></el-option>
                    <el-option label="账户扣款" value="账户扣款"></el-option>
                    <el-option label="线上充值" value="线上充值"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发票种类" prop="invoiceType">
                  <el-select v-model="customerForm.invoicingType" placeholder="请选择">
                    <el-option label="增值税专用电子发票6%" value="type1"></el-option>
                    <el-option label="增值税专用电子电子发票9%" value="type2"></el-option>
                    <el-option label="增值税专用电子发票11%" value="type2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发票抬头" prop="invoiceTitle">
                  <el-input v-model="customerForm.invTitle" placeholder="请输入发票抬头"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="税号" prop="taxNumber">
                  <el-input v-model="customerForm.taxpayerNumber" placeholder="请输入税号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="银行卡号" prop="bankCardNumber">
                  <el-input v-model="customerForm.invBankNum" placeholder="请输入银行卡号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开户行" prop="openingBank">
                  <el-input v-model="customerForm.invBankName" placeholder="请输入开户行"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="财务姓名" prop="financialName">
                  <el-input v-model="customerForm.financePerson" placeholder="请输入财务姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="财务电话" prop="financialPhone">
                  <el-input v-model="customerForm.financeMobile" placeholder="请输入财务电话"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="绑定仓库"
      :visible.sync="warehouseDialogVisible"
      width="80%">
            <!-- 绑定仓库的操作按钮 -->
            <div style="margin-bottom: 20px;">
              <el-button type="primary" @click="bindWarehouse">绑定</el-button>
              <el-button>解绑</el-button>
            </div>

            <!-- 仓库数据表格 -->
            <el-table :data="detailList" style="width: 100%" border>
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="whCode" label="仓库编号" sortable></el-table-column>
              <el-table-column prop="whName" label="仓库名称" sortable></el-table-column>
              <el-table-column prop="warehouseType" label="仓库类型"></el-table-column>
              <el-table-column prop="settlementCurrency" label="结算币种"></el-table-column>
              <el-table-column prop="contactInfo" label="联系信息"></el-table-column>
              <el-table-column prop="provinceCity" label="州省/城市"></el-table-column>
              <el-table-column prop="address" label="地址信息"></el-table-column>
            </el-table>
    </el-dialog>

    <!-- 绑定运输产品对话框 -->
    <el-dialog
      title="绑定运输产品"
      :visible.sync="transportDialogVisible"
      width="60%">
      <el-form :model="transportForm">
        <el-form-item label="客户名称">
          <el-input v-model="transportForm.customerName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="选择运输产品">
          <el-select v-model="transportForm.productId" placeholder="请选择运输产品">
            <el-option label="产品A" value="A"></el-option>
            <el-option label="产品B" value="B"></el-option>
            <el-option label="产品C" value="C"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="transportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="bindTransportSubmit">绑定</el-button>
      </div>
    </el-dialog>

    <!-- 账号管理对话框 -->
    <el-dialog
      title="账号管理"
      :visible.sync="accountDialogVisible"
      width="60%">
      <el-table :data="accountList" stripe style="width: 100%">
        <el-table-column prop="accountNumber" label="账号"></el-table-column>
        <el-table-column prop="balance" label="余额"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" @click="editAccount(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteAccount(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="accountDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog
      title="账户充值"
      :visible.sync="rechargeDialogVisible"
      width="50%">
      <el-form
        ref="rechargeForm"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="100px"
        label-position="right">
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="rechargeForm.accountName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input type="number" v-model.number="rechargeForm.amount" placeholder="请输入充值金额"></el-input>
        </el-form-item>
        <el-form-item label="充值方式" prop="method">
          <el-select v-model="rechargeForm.method" placeholder="请选择充值方式">
            <el-option label="银行转账" value="transfer"></el-option>
            <el-option label="支付宝" value="alipay"></el-option>
            <el-option label="微信支付" value="wechat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="rechargeForm.remark"
            placeholder="请输入备注信息"
            maxlength="100"
            show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRecharge">确认充值</el-button>
      </div>
    </el-dialog>

    <!-- 交易流水对话框 -->
    <el-dialog
      title="交易流水"
      :visible.sync="transactionDialogVisible"
      width="70%">
      <el-table :data="transactionHistory" stripe style="width: 100%">
        <el-table-column prop="date" label="交易日期"></el-table-column>
        <el-table-column prop="type" label="交易类型"></el-table-column>
        <el-table-column prop="amount" label="金额">
          <template slot-scope="scope">
            <span :class="scope.row.amount < 0 ? 'amount-red' : 'amount-green'">
              ¥{{ formatAmount(scope.row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="交易后余额">
          <template slot-scope="scope">
            <span :class="scope.row.balance < 0 ? 'amount-red' : 'amount-green'">
              ¥{{ formatAmount(scope.row.balance) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="transactionDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

<!-- 仓库绑定对话框   -->
    <el-dialog
      title="绑定仓库"
      :visible.sync="dialogVisible1"
      width="30%"
      @closed="clearSelection">
      <div class="bind-warehouse-container">
        <el-form>
          <el-form-item label="关联仓库">
            <el-select
              v-model="selectedWarehouse"
              placeholder="请选择仓库"
              style="width: 100%">
              <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.whName"
                :value="warehouse.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TabProfile from './tab-profile.vue';
import TabAccount from './tab-account.vue';
import * as API_Customer from '@/api/archives/customer';
import { addDetail, listDetail } from '@/api/archives/customerWarehouseDetail';
import { getToken } from '@/utils/auth';
import { listWarehouse } from '@/api/system/warehouse';

export default {
  name: 'pg-customer',
  components: {
    TabProfile,
    TabAccount
  },
  data() {
    return {
      uploadAction: process.env.VUE_APP_BASE_API + '/file/upload', // 文件上传接口地址（根据若依框架的实际接口调整）
      uploadHeaders: { Authorization: localStorage.getItem('token') },
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      activeTab: 'profile',
      imageUrl: '',
      dialogVisible: false,
      activeFormTab: '基本信息',
      searchForm: {
        customerCode: '',
        customerName: '',
        shortName: '',
        contact: '',
        salesman: ''
      },
      dialogVisible1: false,
      customerList: [],
      customerForm: {
        cusCode: '',
        shortName: '',
        fullName: '',
        businessType: '',
        customerType: '',
        salesman: '',
        platform: '',
        contact: '',
        contactPhone: '',
        address: '',
        remark: '',
        logo: '',
        settlementCurrency: '',
        settlementMethod: '',
        settlementCycle: '',
        paymentMethod: '',
        invoiceType: '',
        invoiceTitle: '',
        taxNumber: '',
        bankCardNumber: '',
        openingBank: '',
        financialName: '',
        financialPhone: ''
      },
      rules: {},
      settlementRules: {
        settlementCurrency: [{ required: true, message: '请选择结算币种', trigger: 'change' }]
      },
      isEdit: false, // 是否是编辑状态
      currentEditId: null, // 当前编辑的客户ID
      selectedWarehouse: null,
      // 绑定仓库相关
      warehouseDialogVisible: false,
      warehouseForm: {
        customerName: '',
        warehouseId: ''
      },

      // 绑定运输产品相关
      transportDialogVisible: false,
      transportForm: {
        customerName: '',
        productId: ''
      },

      // 账号管理相关
      accountDialogVisible: false,
      accountList: [
        { accountNumber: '123456789', balance: '1000.00', status: '正常' },
        { accountNumber: '987654321', balance: '5000.00', status: '正常' }
      ],

      // API信息相关
      apiDialogVisible: false,
      apiForm: {
        apiKey: 'api_1234567890',
        secretKey: 'secret_0987654321',
        baseUrl: 'https://api.example.com'
      },

      // 客户账户相关
      accountSearchForm: {
        customer: '',
        accountName: '',
        bank: '',
        bankAccount: '',
        city: ''
      },
      totalAvailableBalance: 0,

      // 充值相关
      rechargeDialogVisible: false,
      rechargeForm: {
        accountName: '',
        amount: null,
        method: '',
        remark: ''
      },
      rechargeRules: {
        amount: [
          { required: true, message: '请输入充值金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额必须大于0', trigger: 'blur' }
        ],
        method: [
          { required: true, message: '请选择充值方式', trigger: 'change' }
        ]
      },

      // 交易流水相关
      transactionDialogVisible: false,
      activeWarehouseTab: '基本信息',
      transactionHistory: [
        { date: '2023-11-01', type: '充值', amount: 1000, balance: 1000, remark: '客户充值' },
        { date: '2023-11-05', type: '消费', amount: -200, balance: 800, remark: '服务费用' },
        { date: '2023-11-10', type: '充值', amount: 500, balance: 1300, remark: '客户充值' },
        { date: '2023-11-15', type: '消费', amount: -300, balance: 1000, remark: '服务费用' }
      ],

      // 充值审核相关
      auditSearchForm: {
        customer: '',
        channel: '',
        ticket: '',
        applicant: '',
        auditor: '',
        dateRange: []
      },
      detailList: [],
      warehouseList: [],
      warehouseDetailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: '',
        cusAbbName: ''
      },
      warehouseDetailSaveForm: {
        customerId: '',
        cusAbbName: '',
        warehouseId: null,
        whCode: null,
        whName: null
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      auditTableData: [
        {
          index: 1,
          customerName: '客户A',
          status: '待审核',
          amount: 1000,
          receivedAmount: 1000,
          exchangeRate: '1:1',
          ticket: 'TICKET001',
          channel: '银行转账',
          applicant: '张三',
          applyTime: '2023-11-01 10:00:00'
        },
        {
          index: 2,
          customerName: '客户B',
          status: '已通过',
          amount: 500,
          receivedAmount: 500,
          exchangeRate: '1:1',
          ticket: 'TICKET002',
          channel: '支付宝',
          applicant: '李四',
          applyTime: '2023-11-02 14:30:00'
        },
        {
          index: 3,
          customerName: '客户C',
          status: '已拒绝',
          amount: 2000,
          receivedAmount: 1800,
          exchangeRate: '1:1',
          ticket: 'TICKET003',
          channel: '微信支付',
          applicant: '王五',
          applyTime: '2023-11-03 09:15:00'
        }
      ]
    };
  },
  created() {
    this.calculateTotalAvailableBalance();
  },
  methods: {
    // 获取客户列表
    getList() {
      this.$msgSuccess('删除成功');
      this.loading = true;
      API_Customer.listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows.map(item => ({
          ...item,
          availableBalance: this.calculateAvailableBalance(item)
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    /**
      * @date 2025/07/01
      * @author wolfMan
      * @description {账户为0的行报警告}
    */
    tableWarningClassName ({ row }) {
      if (!row.accountAmount) {
        return 'table-warning-row';
      };
    },
    // 计算可用余额 (账户余额 + 授信额度)
    calculateAvailableBalance(row) {
      const accountAmount = parseFloat(row.accountAmount || 0);
      const creditAmount = parseFloat(row.creditAmount || 0);
      return accountAmount + creditAmount;
    },
    // 格式化金额显示
    formatAmount(value) {
      return value || 0;
    },
    handleTabClick(tab) {
      console.log('切换到选项卡:', tab.name);
    },
    clearSelection() {
      this.selectedWarehouse = null;
    },
    search() {
      console.log('查询客户档案', this.searchForm);
    },
    reset() {
      this.searchForm = {
        customerCode: '',
        customerName: '',
        shortName: '',
        contact: '',
        salesman: ''
      };
    },
    bindWarehouse(){
      this.dialogVisible1 =true;
      this.getWarehouseList();
    },
    // 打开添加客户表单
    addCustomer() {
      this.isEdit = false;
      this.currentEditId = null;
      this.resetForm();
      this.dialogVisible = true;
    },
    // 打开编辑客户表单
    editCustomer(row) {
      this.isEdit = true;
      this.currentEditId = row.id;
      this.resetForm();
      this.dialogVisible = true;
      this.customerForm = { ...row };
    },
    // 重置表单
    resetForm() {
      this.customerForm = {};
      this.activeFormTab = '基本信息';
    },
    // 提交表单
    submitForm() {
      this.$refs['customerForm'].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.updateCustomer();
          } else {
            this.createCustomer();
          }
        } else {
          this.$message.error('请填写必填字段');
        }
      });
    },
    // 创建客户
    createCustomer() {
      API_Customer.addCustomer(this.customerForm).then(() => {
        this.$message.success('客户创建成功');
        this.dialogVisible = false;
        this.getList();
      }).catch(error => {
        console.error('创建客户失败', error);
        this.$message.error('创建客户失败');
      });
    },
    // 更新客户
    updateCustomer() {
      const data = {
        id: this.currentEditId,
        ...this.customerForm
      };
      API_Customer.updateCustomer(data).then(() => {
        this.$message.success('客户更新成功');
        this.dialogVisible = false;
        this.getList();
      }).catch(error => {
        console.error('更新客户失败', error);
        this.$message.error('更新客户失败');
      });
    },
    exportData() {
      this.$message.success('导出客户档案数据功能已触发');
    },
    handleCommand(command, row) {
      console.log('执行命令:', command, row);
      switch (command) {
        case 'bindWareHouse':
          this.showWarehouseDialog(row);
          break;
        case 'bindCarryProduct':
          this.showTransportDialog(row);
          break;
        case 'accountManage':
          this.showAccountDialog(row);
          break;
        case 'getApiInfo':
          this.showApiDialog(row);
          break;
        case 'removeCustomer':
          this.removeCustomer(row);
          break;
        default:
          console.log('未知命令');
      }
    },
    // 显示绑定仓库对话框
    showWarehouseDialog(row) {
      this.warehouseDetailQueryParams.customerId = row.id;
      this.warehouseDetailQueryParams.cusAbbName = row.cusAbbName;
      this.warehouseDetailSaveForm.customerId = row.id;
      this.warehouseDetailSaveForm.cusAbbName = row.cusAbbName;
      this.getWarehouseDetailList();
      this.warehouseDialogVisible = true;
    },
    getWarehouseDetailList() {
      listDetail(this.warehouseDetailQueryParams).then(response => {
        console.log('仓库信息',response);
        this.detailList = response.rows;
        this.pagination.total = response.total;
      });
    },
    getWarehouseList() {
      listWarehouse(this.queryParams).then(response => {
        console.log('绑定仓库下拉查询',response);
        this.warehouseList = response.rows;
      });
    },
    // 显示绑定运输产品对话框
    showTransportDialog(row) {
      this.transportForm.customerName = row.cusName;
      this.transportDialogVisible = true;
    },
    // 显示账号管理对话框
    showAccountDialog() {
      this.accountDialogVisible = true;
    },
    // 显示API信息对话框
    showApiDialog() {
      this.apiDialogVisible = true;
    },
    // 绑定仓库提交
    bindWarehouseSubmit() {
      if (!this.warehouseForm.warehouseId) {
        this.$message.error('请选择仓库');
        return;
      }
      console.log('绑定仓库:', this.warehouseForm);
      this.warehouseDialogVisible = false;
    },
    // 绑定运输产品提交
    bindTransportSubmit() {
      if (!this.transportForm.productId) {
        this.$message.error('请选择运输产品');
        return;
      }
      console.log('绑定运输产品:', this.transportForm);
      this.transportDialogVisible = false;
    },
    // 重新生成API密钥
    regenerateApiKeys() {
      this.apiForm.apiKey = 'api_' + Math.random().toString(36).substring(2, 10);
      this.apiForm.secretKey = 'secret_' + Math.random().toString(36).substring(2, 10);
      this.$message.success('API密钥已重新生成');
    },
    // 删除客户
    removeCustomer(row) {
      const ids = row.id || this.ids;
      this.$confirm(`是否确认删除主单费用编号为 ${ids} 的数据项？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API_Customer.delCustomer(ids).then(response => {
          // 数据请求成功
          if (response.success) {
            this.$msgSuccess('删除成功');
            this.getList();
          } else {
            this.$msgError(response.msg);
          };
        });
      }).catch(() => {
        console.log('取消');
      });
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
        return false;
      }
      return true;
    },

    // 文件上传成功的钩子函数
    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.customerForm.logo = response.data.url; // 假设返回的数据中包含图片的 URL
        this.$message.success('图片上传成功');
      } else {
        this.$message.error('图片上传失败：' + response.msg);
      }
    },

    // 客户账户相关方法
    searchAccount() {
      console.log('查询客户账户', this.accountSearchForm);
    },
    resetAccount() {
      this.accountSearchForm = {
        customer: '',
        accountName: '',
        bank: '',
        bankAccount: '',
        city: ''
      };
    },
    exportAccount() {
      this.$message.success('导出客户账户数据功能已触发');
    },
    // 表格行样式
    tableRowClassName({ row }) {
      if (parseFloat(row.accountBalance) < 0) {
        return 'negative-balance-row';
      }
      return '';
    },
    // 获取金额显示样式
    getAmountClass(value) {
      return value < 0 ? 'amount-red' : 'amount-green';
    },
    // 充值相关方法
    recharge(row) {
      this.rechargeForm.accountName = row.accountName;
      this.rechargeDialogVisible = true;
    },
    showTransactionHistory() {
      this.transactionDialogVisible = true;
    },
    editAccount() {
      this.editAccountDialogVisible = true;
    },
    submit(){
      if (this.selectedWarehouse) {
        // 在这里执行绑定操作
        const selectedWarehouseList = this.warehouseList.find(
          (warehouse) => warehouse.id === this.selectedWarehouse
        );

        this.warehouseDetailSaveForm.whName=selectedWarehouseList.whName;
        this.warehouseDetailSaveForm.warehouseId = selectedWarehouseList.id;
        this.warehouseDetailSaveForm.whCode = selectedWarehouseList.whCode;
        addDetail(this.warehouseDetailSaveForm).then(() => {
          this.$modal.msgSuccess('新增成功');
          this.dialogVisible1 = false;
          this.getWarehouseDetailList(this.warehouseDetailQueryParams);
        });
        console.log('选中的仓库:', selectedWarehouseList);
        this.dialogVisible = false;
      } else {
        this.$message.warning('请选择一个仓库');
      }
    },
    submitRecharge() {
      this.$refs['rechargeForm'].validate((valid) => {
        if (valid) {
          this.$message.success('充值请求已提交');
          this.rechargeDialogVisible = false;
          // 在实际应用中，这里应该调用API提交充值请求
        } else {
          this.$message.error('请填写完整的充值信息');
        }
      });
    }
  }
};
</script>

<style scoped>
::v-deep .el-table .table-warning-row {
  background-color: #f6dcdc !important;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.customer-modal {
  text-align: left;
}

.custom-dialog {
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

.el-tabs {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.tab-content {
  /* padding: 20px; */
}

.action-bar {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}

.hint {
  margin-bottom: 20px;
}

/* 金额字段样式 */
.amount-green {
  color: #67C23A;
}

.amount-red {
  color: #F56C6C;
}

/* 负余额行背景 */
.negative-balance-row {
  background-color: rgba(255, 0, 0, 0.1) !important;
}

/* 金额字段样式 */
.amount-green {
  color: #67C23A;
}

.amount-red {
  color: #F56C6C;
}

/* 合计行样式 */
.total-row {
  margin-top: 20px;
  font-size: 16px;
  font-weight: bold;
}

.total-amount {
  color: #67C23A;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.tab-content {
  /* padding: 20px; */
}

.action-bar {
  margin-bottom: 20px;
}
</style>
